#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pthread.h>


static pthread_mutex_t mutex;
int8_t share[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

void *thread1(void *arg)
{
	int32_t i;
	int32_t lenght;
	int restul;
	
	lenght = sizeof(share)/sizeof(share[0]);
	while(1)
	{
		//加锁
		restul = pthread_mutex_lock(&mutex);
		if(restul != 0)
		{
			printf("pthread_mutex_lock error code %d\n", restul);
			continue;
		}
		
		//倒序
		for(i=0; i<lenght/2; i++)
		{
			//share[i]与share[lenght-1-i]进行交换
			share[i] = share[i] + share[lenght-1-i];
			share[lenght-1-i] = share[i] - share[lenght-1-i];
			share[i] = share[i] - share[lenght-1-i];
		}
		
		//解锁
		pthread_mutex_unlock(&mutex);
		
		//需要宏定义"_GNU_SOURCE"
		pthread_yield();
	}
}

void *thread2(void *arg)
{
	int32_t i;
	int32_t lenght;
	int restul;
	
	lenght = sizeof(share)/sizeof(share[0]);
	while(1)
	{
		//加锁
		restul = pthread_mutex_lock(&mutex);
		if(restul != 0)
		{
			printf("pthread_mutex_lock error code %d\n", restul);
			continue;
		}
		
		for(i=0; i<lenght; i++)
		{
			printf("%d ", share[i]);
		}
		printf("\r\n");
		
		//解锁
		pthread_mutex_unlock(&mutex);
		
		pthread_yield();
	}
}

int main(int argv, char *argc[])
{
	int restul;
	void *exit_value;
	pthread_mutexattr_t attr;
	pthread_t tid1,tid2;
	
	restul = pthread_mutexattr_init(&attr);
	if(restul != 0)
	{
		printf("pthread_mutexattr_init error code %d\r\n", restul);
		return 0;
	}
	restul = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
	if(restul != 0)
	{
		printf("pthread_mutexattr_settype error code %d\r\n", restul);
		return 0;
	}
	//初始化互斥锁
	restul = pthread_mutex_init(&mutex, &attr);
	if(restul != 0)
	{
		printf("pthread_mutexattr_settype error code %d\r\n", restul);
		return 0;
	}
	
	//创建线程
	restul = pthread_create(&tid1, NULL, thread1, "this thread1");
	if(restul != 0)
	{
		printf("pthread_create: error code %d\r\n", restul);
		return -1;
	}
	restul = pthread_create(&tid2, NULL, thread2, "this thread2");
	if(restul != 0)
	{
		printf("pthread_create: error code %d\r\n", restul);
		return -1;
	}
	
	//主线程不能退出
	while(1)
	{
		sleep(10);
	}
}
